import com.netflix.loadbalancer.ILoadBalancer;
import com.netflix.loadbalancer.LoadBalancerBuilder;
import com.netflix.loadbalancer.Server;
import com.netflix.loadbalancer.reactive.LoadBalancerCommand;
import rx.Observable;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

public class Main {
    public static void main(String[] args) {

        // 服务列表
        List<Server> servers = new ArrayList<>();
        servers.add(new Server("localhost", 8084));
        servers.add(new Server("localhost", 8085));
        ILoadBalancer loadBalancer = LoadBalancerBuilder.newBuilder().buildFixedServerListLoadBalancer(servers);
        // 构建负载实例
        for (int i = 0; i < 5; i++) {
            try {
                String returnStr = LoadBalancerCommand.<String>builder().withLoadBalancer(loadBalancer).build().submit(server -> {
                    String addr = "http://" + server.getHostPort() + "/queryOrder";
                    System.out.println("调用地址：" + addr);
                    URL url;
                    try {
                        url = new URL(addr);
                        System.out.println(url.getPath());
                        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                        connection.setRequestMethod("GET");
                        connection.connect();
                        InputStream inputStream = connection.getInputStream();
                        byte[] bytes = new byte[inputStream.available()];
                        int length = inputStream.read(bytes);
                        System.out.println("字节数：" + length);
                        return Observable.just(new String(bytes));
                    } catch (Exception e) {
                        throw new RuntimeException(e.getCause());
                    }
                }).toBlocking().first();
                System.out.println(returnStr);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }
}
